package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.R1;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.PageDto;
import com.itheima.ydd.dto.ShowDto;
import com.itheima.ydd.dto.YddArticleDto;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.entity.YddCate;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.*;
import com.itheima.ydd.service.IYddCateService;
import com.itheima.ydd.service.IYddUserService;
import com.itheima.ydd.utils.JwtUtils;
import com.itheima.ydd.vo.*;
import com.itheima.ydd.vo.IndexVo;
import com.itheima.ydd.vo.YddArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 */
@RestController
@RequestMapping("/index")
@Slf4j
@CrossOrigin
public class SysUserController {

    @Autowired
    private IYddArticleService yddArticleService1;
    @Autowired
    private IYddCateService yddCateService;
    @Autowired
    private IYddUserService yddUserService;
    @Autowired
    private IYddArticleService yddArticleService;
    @Autowired
    private IYddUserDataService yddUserDataService;

    /**
     * 文章列表数据
     *
     * @param page
     * @param limit
     * @param cateid
     * @return
     */
    @GetMapping("/list")
    public R page(int page, int limit, int cateid) {
        //分页查询拦截器
        Page<YddArticle> pageInfo = new Page(page, limit);
        //条件构造器
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddArticle::getCateid, cateid);
        //查询
        yddArticleService1.page(pageInfo,queryWrapper);
        List<YddArticle> records = pageInfo.getRecords();
        List<YddArticleVo> yddArticleVos = records.stream().map((yddArticle) -> {
            YddArticleVo yddArticleVo = new YddArticleVo();
            BeanUtils.copyProperties(yddArticle, yddArticleVo);
            YddCate byId = yddCateService.getById(yddArticleVo.getCateid());
            yddArticleVo.setCatename(byId.getCatename());
            return yddArticleVo;
        }).collect(Collectors.toList());

        PageDto pageDto = new PageDto();
        pageDto.setPageSize(limit);
        pageDto.setCurrentPage(page);
        pageDto.setCount((int)pageInfo.getTotal());
        pageDto.setTotalPages((int)pageInfo.getPages());
        pageDto.setData(yddArticleVos);

//        Map<String, Object> ret = new HashMap<>();
//        ret.put("list", pageDto);

        return R.success("list",pageDto);
    }
    /**
     * 注册
     *
     * @param yddUser
     * @return
     */
    @PostMapping("/reg")
    public R<String> add(@RequestBody YddUser yddUser) {
        log.info("用户注册信息" + yddUser);

        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUser::getMobile, yddUser.getMobile());
        YddUser user1 = yddUserService.getOne(queryWrapper);
        if (!ObjectUtils.isEmpty(user1)) {
            throw new BusinessException("账号已经存在!");
        }

        //接收前端发来的密码  将密码经md5处理
        String password = yddUser.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        String mobile = yddUser.getMobile();

        //封装用户信息
        YddUser user = new YddUser();
        user.setPassword(password);
        user.setMobile(mobile);
        user.setUsername(mobile);

        yddUserService.save(user);

        //将结果返还给前端 将用户 id 和用户名存入 token
        HashMap<String, Object> retMap = new HashMap<>();
        Map<String,Object> tokenMap = new HashMap<>();
        String phone = user.getMobile()
                .replace("[","")
                .replace("]", "")
                .replace("\"", "");
        tokenMap.put("Userid", user.getId());
        tokenMap.put("mobile", phone);

        String token = JwtUtils.getToken(tokenMap);
        retMap.put("token",token);

        return R.success("token",JwtUtils.getToken(tokenMap));
    }

    /**
     * 热门置顶文章数据(首页)
     *
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/new")
    public ResultData New(int page, int limit) {

        //构造分页构造器对象
        Page<YddArticle> pageInfo = new Page(page, limit);

        /*//获取当前时间
        long toDay = System.currentTimeMillis();
        //一周之前的时间
        Long beFore = toDay - 60 * 60 * 24 * 7;*/

        //构造条件 查询一周之内的数据
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(YddArticle::getTitle,YddArticle::getAuthor,YddArticle::getKeywords,YddArticle::getDescription
                ,YddArticle::getTags,YddArticle::getIstop,YddArticle::getIshot,YddArticle::getCreateDate
                ,YddArticle::getClick,YddArticle::getPic,YddArticle::getLovenum,YddArticle::getCateid)
                .between(YddArticle::getCreateDate,"1577376800000","1668782345942");
        HashMap<String, Object> res = yddArticleService1.selectByPage(pageInfo,wrapper);

        return ResultData.ok("", res);
    }
    /**
     * 最新文章
     *
     * @return
     */
    @GetMapping("/hot")
    public ResultData Hot() {

        //YddArticle  Cate 组合信息
        HotVo yddArticlesCate = yddArticleService.YddArticleCatelist();

        return ResultData.ok("", yddArticlesCate);
    }
    /**
     * 推荐文章
     *
     * @return
     */
    @GetMapping("/recommend")
    public ResultData recommend() {

        //YddArticle  Cate 组合信息
        HotVo yddArticlesCate = yddArticleService.YddArticleCatelist();

        return ResultData.ok("", yddArticlesCate);
    }

    /**
     * 首页和全局数据
     *
     * @return
     */
    @GetMapping("/index")
    public ResultData Index() {

        IndexVo res = yddUserService.selectIndex();

        return ResultData.ok("",res);
    }

    /**
     * 展示文章详细信息
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/show")
    public R1<ShowDto> show(Integer id, HttpServletRequest request) {
        ShowDto showDto = new ShowDto();
        //获取当前用户id
        Integer userId = yddUserService.getUserId(request);
        //获取文章信息
        YddArticle article = yddArticleService.getById(id);
        //
        YddArticleDto yddArticleDto = new YddArticleDto();
        BeanUtils.copyProperties(article,yddArticleDto);
        //获取点赞信息
        LambdaQueryWrapper<YddUserData> dianQueryWrapper = new LambdaQueryWrapper<>();
        dianQueryWrapper.eq(YddUserData::getUserId, userId);
        dianQueryWrapper.eq(YddUserData::getArticleId, article.getId());
        List<YddUserData> yddUserDataList = yddUserDataService.list(dianQueryWrapper);
        if(!CollectionUtils.isEmpty(yddUserDataList)){
            for (YddUserData yddUserData : yddUserDataList) {
                Integer idd = yddUserData.getType();
                if(idd==1){
                    yddArticleDto.setCollect(true);
                }else if(idd==2){
                    yddArticleDto.setLike(true);
                }

            }
        }else {
            yddArticleDto.setLike(false);
            yddArticleDto.setCollect(false);
        }
        //获取分类名称
        YddCate yddCate = yddCateService.getById(yddArticleDto.getCateid());
        String cateName= yddCate.getCatename();
        yddArticleDto.setCateName(cateName);

        showDto.setInfo(yddArticleDto);
        //获取上一篇信息
        List<HashMap> prev = new ArrayList<>();
        YddArticle article1 = yddArticleService.getById(id-1);
        if(article1!=null){
            HashMap<String,Object> map = new HashMap<>();
            map.put("id",(id-1));
            map.put("title",article1.getTitle());
            prev.add(map);
        }
        showDto.setPrev(prev);
        //获取下一篇信息
        List<HashMap> next = new ArrayList<>();
        YddArticle article2 = yddArticleService.getById(id+1);
        if(article2!=null){
            HashMap<String,Object> map = new HashMap<>();
            map.put("id",(id+1));
            map.put("title",article2.getTitle());
            prev.add(map);
        }
        showDto.setNext(next);
        //获取推荐信息
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddArticle::getCateid,yddArticleDto.getCateid()).last("limit 8");
        List<YddArticle> list = yddArticleService.list(queryWrapper);
        showDto.setRecommend(list);

        return R1.success(showDto);

    }

   /* @GetMapping("/show")
    public R show(Integer id, HttpServletRequest request) {
        ShowDto showDto = new ShowDto();
        //获取当前用户id
        Integer userId = yddUserService.getUserId(request);
        //获取文章信息
        YddArticle article = yddArticleService.getById(id);
        //
        YddArticleDto yddArticleDto = new YddArticleDto();
        BeanUtils.copyProperties(article,yddArticleDto);
        //获取点赞信息
        LambdaQueryWrapper<YddUserData> dianQueryWrapper = new LambdaQueryWrapper<>();
        dianQueryWrapper.eq(YddUserData::getUserId, userId);
        dianQueryWrapper.eq(YddUserData::getArticleId, article.getId());
        List<YddUserData> yddUserDataList = yddUserDataService.list(dianQueryWrapper);
        if(!CollectionUtils.isEmpty(yddUserDataList)){
            for (YddUserData yddUserData : yddUserDataList) {
                Integer idd = yddUserData.getType();
                if(idd==1){
                    yddArticleDto.setCollect(true);
                }else if(idd==2){
                    yddArticleDto.setLike(true);
                }

            }
        }else {
            yddArticleDto.setLike(false);
            yddArticleDto.setCollect(false);
        }
        //获取分类名称
        YddCate yddCate = yddCateService.getById(yddArticleDto.getCateid());
        String cateName= yddCate.getCatename();
        yddArticleDto.setCateName(cateName);

        showDto.setInfo(yddArticleDto);
        //获取上一篇信息
        List<HashMap> prev = new ArrayList<>();
        YddArticle article1 = yddArticleService.getById(id-1);
        if(article1!=null){
            HashMap<String,Object> map = new HashMap<>();
            map.put("id",(id-1));
            map.put("title",article1.getTitle());
            prev.add(map);
        }
        showDto.setPrev(prev);
        //获取下一篇信息
        List<HashMap> next = new ArrayList<>();
        YddArticle article2 = yddArticleService.getById(id+1);
        if(article1!=null){
            HashMap<String,Object> map = new HashMap<>();
            map.put("id",(id+1));
            map.put("title",article2.getTitle());
            prev.add(map);
        }
        showDto.setNext(next);
        //获取推荐信息
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddArticle::getCateid,yddArticleDto.getCateid()).last("limit 8");
        List<YddArticle> list = yddArticleService.list(queryWrapper);
        showDto.setRecommend(list);

        return R.success("",showDto);

    }*/
}
